<!-- src/main/resources/static/index.html -->
<!doctype html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>WebSocketHandler Demo</title>
    <style>
        body {
            font-family: system-ui, Arial;
            margin: 20px
        }

        #log {
            border: 1px solid #ddd;
            height: 50vh;
            overflow: auto;
            padding: 8px;
            margin: 10px 0
        }

        input, button {
            padding: 8px
        }
    </style>
</head>
<body>
<h3>原生 WebSocketHandler 聊天示例</h3>

<div>
    用户名：<input id="user" value="Alice">
    <button id="btnConnect">连接</button>
    <button id="btnClose" disabled>断开</button>
</div>

<div id="log"></div>

<div>
    <input id="room" placeholder="房间ID，如 room-1">
    <button id="btnJoin" disabled>加入房间</button>
</div>

<div>
    <input id="msg" style="width:70%" placeholder="消息内容">
    <button id="btnAll" disabled>群发 ALL</button>
    <button id="btnRoom" disabled>发到房间</button>
    <input id="to" placeholder="对方用户">
    <button id="btnTo" disabled>点对点</button>
</div>

<script>
    let ws = null;
    const $ = id => document.getElementById(id);
    const log = (s) => {
        const d = document.createElement('div');
        d.textContent = s;
        $('log').appendChild(d);
        $('log').scrollTop = $('log').scrollHeight;
    };

    $('btnConnect').onclick = () => {
        const user = $('user').value.trim() || 'Guest';
        ws = new WebSocket(`ws://${location.host}/ws/chat?user=${encodeURIComponent(user)}`);
        ws.onopen = () => {
            log('已连接');
            toggle(true);
        };
        ws.onmessage = e => log('<< ' + e.data);
        ws.onclose = () => {
            log('已断开');
            toggle(false);
        };
        ws.onerror = e => log('[错误] ' + e);
    };

    $('btnClose').onclick = () => ws && ws.close();
    $('btnJoin').onclick = () => ws && ws.send('JOIN:' + ($('room').value.trim() || 'room-1'));
    $('btnAll').onclick = () => ws && ws.send('ALL:' + $('msg').value);
    $('btnRoom').onclick = () => ws && ws.send('ROOM:' + ($('room').value.trim() || 'room-1') + ':' + $('msg').value);
    $('btnTo').onclick = () => ws && ws.send('TO:' + ($('to').value.trim() || 'Bob') + ':' + $('msg').value);

    function toggle(connected) {
        $('btnClose').disabled = !connected;
        $('btnJoin').disabled = !connected;
        $('btnAll').disabled = !connected;
        $('btnRoom').disabled = !connected;
        $('btnTo').disabled = !connected;
        $('btnConnect').disabled = connected;
    }
</script>
</body>
</html>
